import React from 'react'
import { connect } from 'react-redux'
import {messages} from "share/common";
import moment from 'moment'
import { Tabs, Spin, Popover, Radio } from 'antd'
import expenseService from 'containers/my-account/expense.service'
import credentialService from "containers/financial-account/credential-definition/credential-definition-service";
import 'styles/financial-management/finance-audit/scan-audit.scss'
import ResizeTable from "components/resize-table/resize-table";
import errorMessage from "share/errorMessage";
const TabPane = Tabs.TabPane;

class CertificatePreview extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [],
      data: [],
      pagination: {
        page: 0,
        total:0,
        pageSize:10,
      },
      loading: false,
      journalType: props.templateCodeList ? props.templateCodeList[0] :  null
    };
  }

  templateName = {
    'GL_EXPENSE': messages('expense-14.key35')/*费用凭证*/,
    'GL_WRITE_OFF': messages('expense-14.key36')/*核销凭证*/,
    'GL_PREPAYMENT_CLEARING': messages('expense-14.key37')/*借款审核中间凭证*/
  };

  componentWillMount() {
    this.getCertificateList();
  };

  getCertificateList = (forceRefresh = false) => {
    const { journalType } = this.state;
    const { params, bookDateType, bookDate } = this.props;
    this.setState({ loading: true });
    let requestParams = Object.assign(params, {journalType, forceRefresh});
    bookDateType === 1001 && (requestParams.tempBookDate = bookDate);
    Promise.all([
      expenseService.getCertificateList(requestParams),
      credentialService.getAllList(params.setOfBooksId)
    ]).then(res => {
      this.setState({ loading: false }, () => {
        let columns = [];
        if (res[1].data.length) {
          res[1].data.map(item => {
            columns.push({
              title: item.ledgerName,
              dataIndex: item.interfaceCode,
              width: 120,
              render: value => <Popover content={value}>{value}</Popover>
            })
          })
        }
        this.setState({ columns, data: res[0].data || [], infoVisible: true });
      });
    }).catch(err => {
      errorMessage(err.response);
      this.setState({ loading: false });
      forceRefresh && this.setState({ data: [] });
    });
  };

  onChangePrewTab = e => {
    this.setState({ journalType: e.target.value }, this.getCertificateList);
  };

  onRefresh = () => {
    this.getCertificateList(true);
  };

  renderTip = () => {
    const { bookDateType, bookDate } = this.props;
    let tip = '';
    if (!bookDate) {
      tip = messages('expense-14.key38')/*记账日期为空，以当前日期生成凭证预览，【审核通过】后对应的日期作为记账日期生成实际凭证*/;
    } else {
      if (bookDateType === 1000) {
        tip = messages('expense-14.key39',{arg1: moment(bookDate).format('YYYY-MM-DD')})/*记账日期：{arg1}，以此日期生成凭证预览*/
      } else {
        tip = messages('expense-14.key40',{arg1: moment(bookDate).format('YYYY-MM-DD')})/*记账日期：{arg1}，基于规则设置，生成凭证预览*/
      }
    }
    return tip;
  };

  render(){
    const { columns, data, pagination, loading } = this.state;
    const { templateCodeList } = this.props;
    return (
      <div className="certificate-preview">
        <Spin spinning={loading}>
          <Radio.Group defaultValue={templateCodeList[0]} onChange={this.onChangePrewTab}>
            {templateCodeList.map(templateCode =>
              <Radio.Button value={templateCode}>{this.templateName[templateCode]}</Radio.Button>
            )}
          </Radio.Group>
          <div className="certificate-preview-tip">
            {this.renderTip()}
            （{messages('expense-14.key41')/*若单据信息修改，请*/}
            <a style={{ margin: '0 6px' }} onClick={this.onRefresh}>
              {messages('expense-14.key42')/*刷新*/}
            </a>
            ）
          </div>
          <ResizeTable
            columns={columns}
            dataSource={data}
            pagination={pagination}
            bordered
            minSize={140}
          />
        </Spin>
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    user: state.login.user,
    authToken: state.main.authToken
  }
}

CertificatePreview.contextTypes = {
  router: React.PropTypes.object
};

export default connect(mapStateToProps)(CertificatePreview);
